import React, { useEffect, useState, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { isEmpty, payIcon, showPayButton, payWayName } from '@/utils/common';
import { Mask, Message, ModalWrap, Radio, RadioGroup } from '@/design';
import { useSelector, useDispatch } from 'umi';

import styles from './paymentModal.less';
import CardPayModal from './CardPayModal';

// 預定信息
export default function (props: any) {
  const { modalVisiable, onClose, onClickSure } = props;
  const { seatNum } = useSelector((state: any) => state.order);
  const { payway } = useSelector((state: any) => state.payment);
  const [cardVisible, setCardVisible] = useState<boolean>(false);
  const [submitLoading, setSubmitLoading] = useState<boolean>(false);
  const [userChoosePayWay, setUserChoosePayWay] = useState('')
  const dispatch = useDispatch();
  const [isApple, setIsApple] = useState(false);

  useEffect(() => {
    fetchPayWay();
    if (showPayButton()) {
      setIsApple(true)
    }
  }, [])

  const handlePaymentWayEdit = (value: string) => {
    setUserChoosePayWay(value);
    setSubmitLoading(false);
  }

  const handlePayment = () => {
    const braId = localStorage.getItem('BRAID');
    const codeId = localStorage.getItem('CODEID');
    setSubmitLoading(true);
    if(userChoosePayWay === 'cardpay') {
      onClose();
      setCardVisible(true);
       return
    }
    if(userChoosePayWay === 'cashpay') {
      return Message.error('你要去tips頁面')
   }
    let callBackUrl = `${window.location.origin}/payment-result/?braId=${braId}&codeId=${codeId}`;

    dispatch({
      type: 'payment/fetchOrderPay',
      payload: {
        orderId: props.orderId,
        payAmount: props.payAmount,
        callBackUrl,
        payCategory: 'pay',
        payWay: userChoosePayWay
      }
    })
    setSubmitLoading(false);
   
  }

  //支付方式
  const fetchPayWay = () => {
    if(props.orderStatus !== 'payed') {
      dispatch({
        type: 'payment/fetchPayWay',
        payload: { diningWay: 'togoBespeak' }
      })
    }
  }

  // const [seatNum, setSeatNum] = useState<number>(4);
  return (<>
    <ModalWrap headName={'付款方式'} modalVisiable={modalVisiable} onClose={onClose} noPadding={true} onClickSure={handlePayment} submitLoading={submitLoading}>
      <ul className={styles.payment_list}>
        <RadioGroup onChange={handlePaymentWayEdit}>
          {payway?.map((item: any) => {
            return <li key={item} className={(!isApple && item === 'applepay') ? styles.dn : ''}>
              <div className={styles.channel_info} key={item}>
                <span><img src={payIcon(item)}></img></span>
                {payWayName.get(item)}
              </div>
              <Radio value={item} name={item}></Radio>
            </li>
          })}
        </RadioGroup>
      </ul>
    </ModalWrap>
    <CardPayModal modalVisiable={cardVisible} onClose={() => setCardVisible(false)} orderNo={props.orderNo} payAmount={props.payAmount}/>
  </>
  )
}